//
//  SearchViewController.m
//  半糖
//
//  Created by RenShuang on 15-9-1.
//  Copyright (c) 2015年 shuang. All rights reserved.
//

#import "SearchViewController.h"
#import "searchCollectionViewCell.h"
#import "ZhuanTiViewController.h"
#import "BoutiqueViewController.h"
#import "BaseHeader.h"
#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define PATH  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"/history.plist"]


@interface SearchViewController ()<UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,retain)UISearchBar *searchBar;
@property(nonatomic,retain)NSMutableArray *historyArr;
@property(nonatomic,retain)UIView *upView;
@property(nonatomic,retain)UIButton *removeButton;
@property(nonatomic,retain)UICollectionView *myCollectionView;
@property(nonatomic,retain)UICollectionViewFlowLayout *flowLayout;

@end

@implementation SearchViewController

- (void)dealloc
{
    [_myCollectionView release];
    [_searchBar release];
    [_upView release];
    [super dealloc];
}

//viewDidLoad只执行一次,但是是在viewWillAppear之前执行
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.view.backgroundColor = [NightHandle shareHandle].viewColor;
    
    [self.myCollectionView reloadData];
    
    //热门搜索按钮的夜间模式
    for (NSInteger i = 0; i<8; i++) {
        UIButton *temp = (UIButton *)[self.view viewWithTag:20000+i];
        temp.backgroundColor = [NightHandle shareHandle].viewColor;
        [temp setTitleColor:[NightHandle shareHandle].wordColor forState:UIControlStateNormal];
    }
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.historyArr = [NSMutableArray arrayWithContentsOfFile:PATH];
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 54, WIDTH, 64)];
    _searchBar.delegate = self;
    _searchBar.barTintColor = [UIColor clearColor];
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    _searchBar.placeholder = @"搜索感兴趣的专题或单品";
    [self.view addSubview:_searchBar];
    [_searchBar release];
    
    
    _upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    _upView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_upView];
    [_upView release];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH/3, 18, WIDTH/3, 44)];
    //titleLabel.backgroundColor = [UIColor greenColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"搜索";
    //label加粗并放大
    titleLabel.font = [UIFont boldSystemFontOfSize:22.];
    [_upView addSubview:titleLabel];
    [titleLabel release];

    
    
    UILabel *searchLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 108, 100, 30)];
    searchLabel.text = @"历史搜索";
    [self.view addSubview:searchLabel];
    [searchLabel release];
    
    [self creatButton];
    
    UILabel *hotLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 250, 100, 30)];
    hotLabel.text = @"热门搜索";
    hotLabel.textColor = [UIColor redColor];
    [self.view addSubview:hotLabel];
    [hotLabel release];
    
    NSArray *hotArr = [NSArray arrayWithObjects:@"抱枕",@"包",@"礼物",@"手表",@"耳机",@"文具",@"杯子",@"钱包", nil];
    
    //热门搜索的按钮
    for (NSInteger i = 0; i < 8; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button.layer setBorderWidth:1.];
        //button.backgroundColor = [UIColor whiteColor];
        button.tag = 20000+i;
        button.titleLabel.font = [UIFont systemFontOfSize:12.];
//        button.layer.masksToBounds = YES;
//        button.layer.cornerRadius = 5;
        [button addTarget:self action:@selector(hotClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[hotArr objectAtIndex:i] forState:UIControlStateNormal];
        CGColorRef grly = [UIColor redColor].CGColor;
        [button.layer setBorderColor:grly];
        [self.view addSubview:button];
        if (i < 5) {
            button.frame = CGRectMake(3*WIDTH/25+i*61*WIDTH/375, 290, 41*WIDTH/375, 25);
        }
        if ((i >= 5)&&(i < 10)) {
            button.frame = CGRectMake(3*WIDTH/25+(i-5)*61*WIDTH/375, 330, 41*WIDTH/375, 25);
        }
    }


    self.removeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.removeButton.frame = CGRectMake(0, 220, WIDTH, 40);
    [self.removeButton setTitle:@"清除历史记录" forState:UIControlStateNormal];
    [self.removeButton addTarget:self action:@selector(removeClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.removeButton];

}


- (void)creatButton
{

    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.itemSize = CGSizeMake(41*WIDTH/375, 25);
    _flowLayout.sectionInset = UIEdgeInsetsMake(5, 3*WIDTH/25, 5, 3*WIDTH/25);
    _flowLayout.minimumInteritemSpacing = 15;
    _flowLayout.minimumLineSpacing = 15;
    
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 140, SCREEN_WIDTH, 65) collectionViewLayout:_flowLayout];
    [self.myCollectionView setBackgroundColor:[NightHandle shareHandle].viewColor];
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    self.myCollectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.myCollectionView];
    [_myCollectionView release];
    [_flowLayout release];

    [self.myCollectionView registerClass:[ButtonCollectionViewCell class] forCellWithReuseIdentifier:@"ButtonCollectionViewCell"];
}

- (void)hotClick:(UIButton *)sender
{
    NSLog(@"%@",sender.titleLabel.text);
    BoutiqueViewController *boutique = [[BoutiqueViewController alloc] init];
    boutique.url_Str = sender.titleLabel.text;
    [self.navigationController pushViewController:boutique animated:YES];
}

- (void)removeClick
{
    //删除沙盒
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (PATH) {
        [fileManager removeItemAtPath:PATH error:nil];
        
        self.historyArr = [[NSMutableArray alloc] init];
        [self.historyArr writeToFile:PATH atomically:YES];
    }
    
    NSArray *receiveArr = [NSArray arrayWithContentsOfFile:PATH];
    NSLog(@"删除后的沙盒数组%@",receiveArr);
    
    
    [self.myCollectionView reloadData];
    
   
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    _searchBar.showsCancelButton = YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    _searchBar.showsCancelButton = NO;
    [_searchBar resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSInteger shaHe = 0;

    self.historyArr = [NSMutableArray arrayWithContentsOfFile:PATH];
    for (NSString *str in self.historyArr) {
        if ([self.searchBar.text isEqualToString:str]) {
            shaHe++;
        }
    }
    if (shaHe == 0) {
        [self.historyArr insertObject:self.searchBar.text atIndex:0];
    }
    NSLog(@"%ld",(unsigned long)self.historyArr.count);
    //数组写入本地的文件后缀使用xml/plist
    [self.historyArr writeToFile:PATH atomically:YES];
    
    BoutiqueViewController *boutique = [[BoutiqueViewController alloc] init];
    boutique.url_Str = self.searchBar.text;
    [self.navigationController pushViewController:boutique animated:YES];
 
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.historyArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ButtonCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ButtonCollectionViewCell" forIndexPath:indexPath];
    
    NSString *texts = [self.historyArr objectAtIndex:indexPath.item];
   
    cell.titleLabel.text = texts;
    cell.contentView.backgroundColor = [NightHandle shareHandle].viewColor;
    cell.titleLabel.textColor = [NightHandle shareHandle].wordColor;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    BoutiqueViewController *boutique = [[BoutiqueViewController alloc] init];
    boutique.url_Str = [self.historyArr objectAtIndex:indexPath.item];
    [self.navigationController pushViewController:boutique animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
